package cn.loioi.web.common;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import cn.loioi.multi.mysql.model.SysResource;


public class BuildMenus {
	public static String builds(List<SysResource> resources, String identity) {
		StringBuffer menu = new StringBuffer(identity);
		for (SysResource res : resources) {
			if (res.getParentid() != 0) continue;
			boolean isOpen = checkIdentity(res.getIdentity(), identity);
			if (isOpen) {
				menu.append("<li class=\"treeview active\">");
			} else {
				menu.append("<li class=\"treeview\">");
			}
			menu.append(a(res.getLinkurl(), res.getIcon(), res.getName(), res.getLabel()));
			menu.append(childrens(resources, identity, res.getId(), isOpen));
			menu.append("</li>");
		}
		return menu.toString();
	}

	private static String childrens(List<SysResource> resources, String identity, Integer id, boolean isOpen) {
		StringBuffer buffer = new StringBuffer();
		for (SysResource res : resources) {
			if (res.getParentid() != id) continue;
			if (checkIdentity(res.getIdentity(), identity)) {
				buffer.append("<li class=\" active\">");
			} else {
				buffer.append("<li>");
			}
			buffer.append(a(res.getLinkurl(), res.getIcon(), res.getName(), res.getLabel()));
			buffer.append("</li>");
		}
		if (buffer.length() > 0) {
			buffer.insert(0, "<ul class=\"treeview-menu" + (isOpen ? " menu-open" : "") + "\">");
			buffer.append("</ul>");
		}
		return buffer.toString();
	}

	public static StringBuffer a(String link, String icon, String name, String label) {
		StringBuffer tmp = new StringBuffer();
		tmp.append("<a href=\"" + (StringUtils.isEmpty(link) ? "#" : link) + "\">");
		tmp.append(getText(icon));
		tmp.append("<span>" + getText(name) + "</span>");
		tmp.append(getText(label));
		tmp.append("</a>");
		return tmp;
	}

	public static boolean checkIdentity(String identity, String root) {
		if (StringUtils.isEmpty(root) || StringUtils.isEmpty(identity)) return false;
		return root.startsWith(identity);
	}

	private static String getText(String str) {
		return StringUtils.isEmpty(str) ? "" : str;
	}
}
